<?php
declare (strict_types = 1);

namespace app\controller;

use app\BaseController;
use app\helpers\traits\SearchDataForModel;
use app\model\AuthGroup;
use app\model\AuthRule;
use app\model\GroupUserPivot;
use think\exception\ValidateException;
use think\Request;

class Role extends BaseController
{
    use SearchDataForModel;

    /**
     * @User: 刘海龙
     * @Date: 2021/2/26
     * @Time: 9:16
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 获取角色列表
     */
    public function roleList()
    {
        $map = [];
        if ($this->request->has('name') && !empty($this->request->param('name'))){
            $map[]  = array('title','like', '%' . $this->request->param('name') . '%');
        }
        //获取每页显示的条数
        $limit = $this->request->param('limit');
        $data = AuthGroup::where($map)->paginate($limit)->each(function ($item, $key) {
            $where=[];
            if ($item['rules'] !== '*') {
                $where[] = array('id','in',$item['rules']);
            }
            $res = AuthRule::where($where)
                ->select()->toArray();

            $item['child'] = AuthRule::sortMenu($res);
            return $item;
        });
        return $this->response($data);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/2/26
     * @Time: 9:18
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 获取所有角色列表
     */
    public function roleInfoList(){
        $res = AuthGroup::select()->toArray();
        return $this->response($res);
    }


    /**
     * @User: 刘海龙
     * @Date: 2021/2/26
     * @Time: 9:19
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 保存角色(中间表)
     */
    public function setRoleUserPivot(){
        $uid = $this->request->param('uid');
        $group_id= $this->request->param('group_id');
        $group_id = explode(',', $group_id);
        $user = \app\model\Admin::find($uid);
        if (is_null($user)) {
            return $this->response(404, '此用户不存在');
        }
        // 删除中间表数据
        $user->roles()->detach();
        $user->roles()->attach($group_id);
        return $this->response();
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/2/26
     * @Time: 9:20
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 新增角色 or 保存
     */
    public function saveRole()
    {
        $id = $this->request->param('id', 0);
        try {
            $validator = $this->validate($this->request->param(),
                \app\validate\Role::rules($id),
                \app\validate\Role::msg());
            if ($validator) {
                if (intval($id) === 0) {
                    $role = new AuthGroup();
                } else {
                    if ($this->request->param('status') == 0 && $user_has_role = GroupUserPivot::where('group_id', $id)->exists()) {
                        return $this->response(501, '该角色已绑定用户，不可禁用');
                    }
                    $role = AuthGroup::find($id);
                }
                $role->title = $this->request->param('title');
                $role->rules = $this->request->param('rules');
                $role->status = $this->request->param('status', 1);
                $role->save();

                return $this->response();
            }
        } catch (ValidateException $exception) {
            return $this->response(403, $exception->getError());
        }
    }


    /**
     * @param $id
     * @param $status
     * @User: 刘海龙
     * @Date: 2021/2/26
     * @Time: 9:20
     * @return \think\response\Json
     * 更新角色状态
     */
    public function updateRoleStatus($id, $status)
    {

        $data = [
            'id' => $id,
            'status' => $status
        ];
        if (intval($id) === 1) {
            return $this->response(403, '超级管理员,不能更改');
        }
        AuthGroup::update($data);
        return $this->response();
    }

    /**
     * @param $id
     * @param $role_id
     * @User: 刘海龙
     * @Date: 2021/2/26
     * @Time: 9:20
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 删除角色
     */
    public function delRole($id, $role_id)
    {
        if (intval($id) === 1) {
            return $this->response(403, '超级管理员,不能删除');
        }
        $res = AuthGroup::find($id);
        $res_arr = explode(',', $res->rules);
        $key = array_search($role_id, $res_arr);
        if ($key === false) {
            return $this->response(403, '未找到该权限');
        }
        array_splice($res_arr, $key, 1);
        $res->rules = implode(',', $res_arr);
        $res->save();
        //重新获取最新的数据展示
        $res = AuthRule::where('id', 'in', $res_arr)
            ->where('is_open', AuthRule::OPEN_ONE)
            ->select()->toArray();
        $data = AuthRule::sortMenu($res);
        return $this->response($data);

    }

    /**
     * @param $id
     * @User: 刘海龙
     * @Date: 2021/2/26
     * @Time: 9:21
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 删除角色组
     */
    public function groupDel($id)
    {
        $ids_array = explode(',', $id);
        foreach ($ids_array as $id) {
            if ($id == 1) {
                return $this->response(501, '管理员不可删除');
            }
            $has_user = GroupUserPivot::where('group_id', $id)->find();
            if ($has_user) {
                return $this->response(501, '该角色已绑定用户，不可删除');
            }
        }
        foreach ($ids_array as $id) {
            AuthGroup::find($id)->force()->delete();
        }
        return $this->response();
    }
}
